package cn.emall.service.impl;

import java.util.Date;
import java.util.List;

import cn.emall.jedis.JedisClient;
import cn.emall.mapper.TbItemDescMapper;
import cn.emall.mapper.TbItemMapper;
import cn.emall.pojo.EasyUIDataGridResult;
import cn.emall.pojo.TbItem;
import cn.emall.pojo.TbItemDesc;
import cn.emall.pojo.TbItemExample;
import cn.emall.utils.EmallResult;
import cn.emall.utils.IDUtils;
import cn.emall.utils.JsonUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import cn.emall.pojo.TbItemExample.Criteria;
import cn.emall.service.ItemService;

import javax.annotation.Resource;
import javax.jms.*;

@Service
public class ItemServiceImpl implements ItemService {

	@Autowired
	private TbItemMapper itemMapper;
	@Autowired
	private TbItemDescMapper itemDescMapper;
	@Autowired
	private JmsTemplate jmsTemplate;
	@Resource
	private Destination topicDestination;
	@Autowired
    private JedisClient jedisClient;
	@Value("${REDIS_ITEM_PRE}")
    private String REDIS_ITEM_PRE;
	@Value("${ITEM_CACHE_EXPIRE}")
    private Integer ITEM_CACHE_EXPIRE;

	@Override
	public TbItem getItemById(long itemId) {
        //查询缓存
	    try {
            String string = jedisClient.get(REDIS_ITEM_PRE + ":" + itemId + ":BASE");
            if(StringUtils.isNotBlank(string))
                return JsonUtils.jsonToPojo(string,TbItem.class);
        }catch (Exception e){
	        e.printStackTrace();
        }
        //缓存中没有，查询数据库
        // 根据主键查询
		// TbItem tbItem = itemMapper.selectByPrimaryKey(itemId);
		TbItemExample example = new TbItemExample();
		Criteria criteria = example.createCriteria();
		criteria.andIdEqualTo(itemId);
		List<TbItem> list = itemMapper.selectByExample(example);
		if (list != null && list.size() > 0) {
            //把结果添加到缓存
		    try {
                jedisClient.set(REDIS_ITEM_PRE + ":" + itemId + ":BASE", JsonUtils.objectToJson(list.get(0)));
                //设置过期时间
                jedisClient.expire(REDIS_ITEM_PRE + ":" + itemId + ":BASE",ITEM_CACHE_EXPIRE);
            }catch (Exception e){
                e.printStackTrace();
            }
			return list.get(0);
		}

		return null;
	}

	@Override
	public EasyUIDataGridResult getItemList(int page, int rows) {
		//设置分页信息
		PageHelper.startPage(page,rows);
		//执行查询
		TbItemExample tbItemExample = new TbItemExample();
		List<TbItem> lists = itemMapper.selectByExample(tbItemExample);
		//创建一个返回对象
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		result.setRows(lists);
		//取分页结果
		PageInfo<TbItem> info = new PageInfo<>(lists);
		//取总记录数
		result.setTotal(info.getTotal());
		return result;
	}

	@Override
	public EmallResult insertItem(TbItem tbItem, String desc) {
		//生成商品id
		final long id = IDUtils.genItemId();
		//补全item的属性
		tbItem.setId(id);
		tbItem.setCreated(new Date());
		tbItem.setUpdated(new Date());
		//1-正常，2-下架，3-删除
		tbItem.setStatus((byte) 1);
		//向商品表插入数据
		itemMapper.insert(tbItem);
		//创建一个商品描述表对应的pojo对象。
		TbItemDesc tbItemDesc = new TbItemDesc();
		//补全属性
		tbItemDesc.setItemId(id);
		tbItemDesc.setItemDesc(desc);
		tbItemDesc.setCreated(new Date());
		tbItemDesc.setUpdated(new Date());
		//向商品描述表插入数据
		itemDescMapper.insert(tbItemDesc);
		jmsTemplate.send(topicDestination, new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				TextMessage textMessage = session.createTextMessage(id + "");
				return textMessage;
			}
		});
		//返回成功
		return EmallResult.ok();
	}

    @Override
    public TbItemDesc getItemDescById(long itemId) {
        //查询缓存
	    try {
            String string = jedisClient.get(REDIS_ITEM_PRE + ":" + itemId + ":DESC");
            if(StringUtils.isNotBlank(string))
                return JsonUtils.jsonToPojo(string,TbItemDesc.class);
        }catch (Exception e){
            e.printStackTrace();
        }
        TbItemDesc tbItemDesc = itemDescMapper.selectByPrimaryKey(itemId);
        //把结果添加到缓存
        try {
            jedisClient.set(REDIS_ITEM_PRE + ":" + itemId + ":DESC", JsonUtils.objectToJson(tbItemDesc));
            //设置过期时间
            jedisClient.expire(REDIS_ITEM_PRE + ":" + itemId + ":DESC",ITEM_CACHE_EXPIRE);
        }catch (Exception e){
            e.printStackTrace();
        }
        return tbItemDesc;
    }

}
